<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { registerService, sendVerificationCode } from '../api/User.js'

const router = useRouter();

// 提示消息状态管理
const message = ref({
  show: false,
  text: '',
  type: 'info' // success/error/info
});

// 显示提示消息（自动消失）
const showMessage = (text, type = 'info', duration = 3000) => {
  message.value = { show: true, text, type };
  setTimeout(() => {
    message.value.show = false;
  }, duration);
};

// 表单数据
const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  verificationCode: ''
});

const postForm = reactive({
  username: '',
  password: '',
  email: '',
  verificationCode: ''
});

const formErrors = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  verificationCode: ''
});

const countdown = ref(0);
const isFormValid = ref(false);

// 监听表单变化进行验证
watch(form, () => {
  validateForm();
});

// 表单验证函数
const validateForm = () => {
  formErrors.username = form.username ? '' : '用户名不能为空';
  formErrors.password = form.password.length >= 6 ? '' : '密码长度至少为6位';
  formErrors.confirmPassword = form.password === form.confirmPassword ? '' : '两次输入的密码不一致';
  formErrors.email = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email) ? '' : '请输入有效的邮箱地址';
  formErrors.verificationCode = form.verificationCode.length === 6 ? '' : '验证码为6位数字';

  isFormValid.value = Object.values(formErrors).every(error => !error);
};

// 发送验证码
const sendCode = async () => {
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
    formErrors.email = '请输入有效的邮箱地址';
    return;
  }

  if (countdown.value > 0) return;

  try {
    const result = await sendVerificationCode({ emailTo: form.email, subject: "注册验证码" });
    if (result.code === 1) {
      showMessage('验证码已发送至邮箱，请注意查收', 'success');
      startCountdown();
    } else {
      showMessage(result.message || '发送验证码失败', 'error');
    }
  } catch (error) {
    showMessage('发送失败: ' + error.message, 'error');
  }
};

// 倒计时功能
const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 处理注册
const handleRegister = async () => {
  validateForm();

  if (!isFormValid.value) {
    return;
  }

  postForm.username = form.username;
  postForm.password = form.password;
  postForm.email = form.email;
  postForm.verificationCode = form.verificationCode;

  try {
    const result = await registerService(postForm);
    console.log(result);
    if (result.code === 1) {
      showMessage('注册成功，即将跳转到登录页', 'success', 2000);
      setTimeout(() => {
        router.push('/login');
      }, 2000); // 延迟跳转，确保用户看到提示
    } else {
      showMessage(result.message || '注册失败', 'error');
      if (result.message === "用户已存在,请直接登录") {
        setTimeout(() => {
          router.push('/login');
        }, 1500);
      }
    }
  } catch (error) {
    showMessage('注册失败: ' + error.message, 'error');
  }
};
</script>


<template>
  <div class="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8 relative overflow-hidden">
    <!-- 全局提示组件 -->
    <div v-if="message.show" :class="['fixed top-6 left-1/2 transform -translate-x-1/2 px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300',
      message.type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' :
        message.type === 'error' ? 'bg-red-50 text-red-700 border border-red-200' :
          'bg-blue-50 text-blue-700 border border-blue-200']">
      <p class="flex items-center gap-2">
        <i v-if="message.type === 'success'" class="icon-check-circle"></i>
        <i v-if="message.type === 'error'" class="icon-exclamation-circle"></i>
        <span>{{ message.text }}</span>
      </p>
    </div>

    <!-- 注册卡片 -->
    <div
      class="max-w-md w-full space-y-8 bg-white/95 backdrop-blur-sm rounded-xl shadow-lg overflow-hidden transform transition-all duration-300 hover:shadow-2xl">
      <div class="relative overflow-hidden">
        <div class="absolute top-0 right-0 -mt-16 -mr-16 w-32 h-32 bg-green-400/20 rounded-full blur-2xl"></div>
        <div class="relative p-8">
          <!-- 标题 -->
          <div class="text-center">
            <h2 class="mt-6 text-3xl font-bold text-gray-900 tracking-tight">
              用户注册
            </h2>
            <div class="w-12 h-1 bg-green-500 rounded-full mx-auto mt-4"></div>
          </div>

          <!-- 注册表单 -->
          <form @submit.prevent="handleRegister" class="relative z-10">
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
              <input type="text" v-model="form.username" required placeholder="请输入用户名"
                class="w-full px-4 py-3 focus:outline-none rounded-lg border border-green-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all bg-gray-50">
              <p class="text-red-500 text-xs mt-1">{{ formErrors.username }}</p>
            </div>

            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-1">密码</label>
              <input type="password" v-model="form.password" required minlength="6" placeholder="请输入密码"
                class="w-full px-4 py-3 focus:outline-none rounded-lg border border-green-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all bg-gray-50">
              <p class="text-red-500 text-xs mt-1">{{ formErrors.password }}</p>
            </div>

            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-1">确认密码</label>
              <input type="password" v-model="form.confirmPassword" required minlength="6" placeholder="确认密码"
                class="w-full px-4 py-3 focus:outline-none rounded-lg border border-green-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all bg-gray-50">
              <p class="text-red-500 text-xs mt-1">{{ formErrors.confirmPassword }}</p>
            </div>

            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
              <div class="flex">
                <input type="email" v-model="form.email" required placeholder="请输入邮箱"
                  class="flex-1 px-4 py-3 focus:outline-none rounded-l-lg border border-green-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all bg-gray-50">
                <button type="button" @click="sendCode"
                  class="px-4 py-3 bg-green-500 text-white font-medium rounded-r-lg shadow hover:bg-green-600 transition-colors"
                  :disabled="countdown > 0">
                  {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
                </button>
              </div>
              <p class="text-red-500 text-xs mt-1">{{ formErrors.email }}</p>
            </div>

            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-1">验证码</label>
              <input type="text" v-model="form.verificationCode" required maxlength="6" placeholder="请输入验证码"
                class="w-full px-4 focus:outline-none py-3 rounded-lg border border-green-300 focus:border-green-500 focus:ring-2 focus:ring-green-200 transition-all bg-gray-50">
              <p class="text-red-500 text-xs mt-1">{{ formErrors.verificationCode }}</p>
            </div>

            <button type="submit"
              class="w-full py-3 px-4 bg-gradient-to-r from-green-500 to-emerald-500 text-white font-medium rounded-lg shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all duration-300"
              :disabled="!isFormValid">
              注册
            </button>

            <div class="mt-6 text-center text-gray-600 text-sm">
              已有账号? <router-link to="/login"
                class=" text-green-600 font-medium hover:text-green-700  transition-colors">立即登录</router-link>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>



<style>
/* 图标样式补充 */
.icon-check-circle {
  color: #10b981;
}

.icon-exclamation-circle {
  color: #ef4444;
}
</style>